<script setup lang="ts">
import { Pagination } from '@/widgets'
import { onMounted, ref, watch } from 'vue'
type ListItem = {
  name: string
  icon?: string
  idx: number
}

const props = defineProps({
  items: {
    type: Array<ListItem>,
    default: () => []
  },
  icon: {
    type: String
  },
  title: {
    type: String,
    default: ''
  }
})

const emits = defineEmits<{
  (e: 'selected', idx: number): void
}>()

let totalContent: ListItem[] = []

const pageContent = ref<ListItem[]>([])
const pageTotalCount = ref(0)
const pageIdx = ref(0)
const pageEntryCount = 10
const selected = ref<ListItem | null>(null)

function select(it: ListItem) {
  selected.value = it
}

function confirm() {
  if (!selected.value) {
    return
  }
  emits('selected', selected.value.idx)
}

function cancel() {
  emits('selected', -1)
}

function updateContent(content: ListItem[]) {
  if (totalContent === content) {
    return
  }
  totalContent = content
  pageContent.value = totalContent.slice(0, pageEntryCount)
  pageTotalCount.value = Math.ceil(totalContent.length / pageEntryCount)
  pageIdx.value = 0
  selected.value = null
}

function updatePage(idx: number) {
  const start = idx * pageEntryCount
  pageContent.value = totalContent.slice(start, start + pageEntryCount)
}

function filter(s: string) {
  if (!s) {
    updateContent(props.items)
    return
  }
  s = s.trim()
  if (s.length === 0) {
    updateContent(props.items)
    return
  }
  const lst = props.items.filter((e) => e.name.toLowerCase().indexOf(s) >= 0)
  updateContent(lst)
}

watch(pageIdx, (idx) => updatePage(idx))

onMounted(() => {
  updateContent(props.items)
})
// function
</script>
<template>
  <div class="list-select pane">
    <div class="pane-heading">
      <div class="pane-title"><i v-if="icon" :class="icon" />{{ title }}</div>
      <div class="pane-tool">
        <i class="mas-icon-close" @click="cancel" />
      </div>
    </div>
    <div class="pane-block">
      <div class="row">
        <input
          class="input"
          type="text"
          placeholder="过滤"
          @input="(evt) => filter((evt.target as HTMLInputElement).value)"
        />
      </div>
      <ul class="menu-list">
        <li v-for="(item, idx) in pageContent" @click="select(item)">
          <a :class="{ 'is-active': item === selected }">
            <i v-if="item.icon" :class="item.icon" />
            {{ item.name }}
          </a>
        </li>
      </ul>
    </div>
    <div class="pane-footer is-space">
      <Pagination :page-count="pageTotalCount" v-model:current-page="pageIdx" />
      <div class="pane-tool">
        <button class="button" @click="cancel">取消</button>
        <button class="button is-primary" :disabled="selected == null" @click="confirm">
          确定
        </button>
      </div>
    </div>
  </div>
</template>
<style lang="scss">
.list-select {
  min-width: 25em;
  max-width: 40em;
  .pagination {
    margin-bottom: 0;
  }
  .pane-block {
    min-height: 24em;
  }
}
</style>
